<template>
    <div class="dataEdit" ref="rq" style="width:100%;display: inline-flex;">
        <div :style="{width:divW+'px', display: 'inline-block'} ">
          <vxe-button status="success" v-if="showedit&&Action['TM']===undefined" content="修改" size="mini" @click="doedit"></vxe-button>
            <vxe-button status="success" v-if="statusCode===0&&canEdit&&Action['TM']===undefined" content="保存" size="mini" @click="Save()"></vxe-button>
            <vxe-button status="success" v-if="formData.StatusCode===0&&[2,5].includes(Template.allowBestFitColumns)" content="提交" size="mini" @click="addTask()"></vxe-button>
            <vxe-button status="success" v-if="formData.StatusCode!==8&&Template.allowBestFitColumns===1" content="审核" size="mini" @click="handleCheck(8)"></vxe-button>
            <vxe-button status="success" v-if="formData.StatusCode===8&&Template.allowBestFitColumns===1" content="反审" size="mini" @click="handleCheck(0)"></vxe-button>
            <vxe-button size="mini" status="primary" transfer placement="bottom" v-for="(items,key) in ManualActRules" :key="key">
              <template #default>{{ key }}</template>
              <template #dropdowns>
                <vxe-button type="text" v-for="(item,index) in items" :content="item.ruleName" :key="index" v-show="item.isExtFlow===0||(item.isExtFlow===1&&![1,2,8].includes(formData.StatusCode))"   @click="runActRules(item)"></vxe-button>
              </template>
            </vxe-button>
          <vxe-button size="mini"  v-if="canPrint" transfer :style="{marginLeft:(Action['TM']==='Print'?'100px':'10px')}">
              <template #default>打印</template>
            <template #dropdowns>
                <vxe-button status="primary" v-if="Template.allowPrintWith===1" @click="handlePrint(-1)" >标准打印</vxe-button>
                <vxe-button  status="primary"  v-if="printTemplates.length>0" v-for="item in printTemplates" @click="handlePrint(item)" >{{ item.name }}</vxe-button>
                <vxe-button status="success" @click="handlePrint(null)" >新建打印模板</vxe-button>
            </template>
          </vxe-button >
          <vxe-button size="mini"  v-if="canPrint" transfer :style="{marginLeft:(Action['TM']==='Print'?'100px':'10px')}">
            <template #default>新版打印</template>
          <template #dropdowns>
              <vxe-button status="primary" v-if="Template.allowPrintWith===1" @click="handlePrint2(-1)" >标准打印</vxe-button>
              <vxe-button  status="primary"  v-if="printTemplates.length>0" v-for="item in printTemplates" @click="handlePrint2(item)" >{{ item.name }}</vxe-button>
          </template>
        </vxe-button >
            <div style="float: right;    font-size: 1.3em;    margin-right: 50px;"> {{ Template.templateTitle }}{{ ![0,8].includes(formData.StatusCode)?'    审批中..':''}}</div>
          <vxe-form :data="formData" :ref="el=>{refForm=el}" :rules="Rules[MT.tableName]" size="small" title-width="100" >
            <vxe-form-item :visible="false" field="RecordID"></vxe-form-item>
            <vxe-form-item v-for="item in  Fields[MT.tableName]" :key="item.fieldID" :span="isequipment?8:24"
                           :title="item.fieldDispName" :visible="item.hidden===0" :field="item.fieldName"
                           :title-width="item.allowFixedWidth>0?item.allowFixedWidth:100" title-overflow
                           :item-render="{events:{change:ValueChange}}">
              <template #default="{ data }">
                <div v-if="item.dataTypeID===1">
                  <vxe-input v-model="data[item.fieldName]" v-show="item.componentID===0" :readonly="item.editable===0||statusCode!==0"
                             @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
                  <el-input size="default" v-show="item.componentID>0" :style="{width:(divW/3-(item.allowFixedWidth>0?item.allowFixedWidth:100)-10)+'px'}"
                            @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                            placeholder="请点击选择..."  :readonly="item.editable===0||statusCode!==0"
                            v-if="item.componentID>0 && [3,6].includes(item.componentType)" type="text"
                            :value="getextend(data,item)">
                    <template #append style="padding: 0 10px">
                      <el-button  class="plusA" :disabled="item.editable===0" @click="showSource({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName})"
                                 size="default" >+</el-button>
                    </template>
                  </el-input>
                  <vxe-select v-if="item.componentID>0 && item.componentType===1" :disabled="item.editable===0||statusCode!==0"
                              v-model="data[item.fieldName]" placeholder="下拉框" :clearable="item.editable===1||statusCode===0"
                              @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" transfer>
                    <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label" :key="index"></vxe-option>
                  </vxe-select>
                  <vxe-input v-if="item.componentID>0 && item.componentType===5" v-model="data[item.fieldName]"
                             :readonly="item.editable===0||statusCode!==0" placeholder="自动取得编号"
                             @suffix-click="getAutoCode( Fields[MT.tableName],formData,item.fieldName,MT.tableName)">
                    <template #suffix><i class="el-icon-refresh-right"></i></template>
                  </vxe-input>
                </div>
                <vxe-input v-if="item.dataTypeID===2" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0"
                           placeholder="请输入..." type="integer"
                           @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
                <vxe-input v-if="item.dataTypeID===3" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0"
                           placeholder="请输入..." :clearable="item.editable===1||statusCode===0" type="float" :digits="item.fieldPrecision"
                           @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
                <vxe-input v-if="item.dataTypeID===4" v-model="data[item.fieldName]" :readonly="item.editable===0||statusCode!==0" transfer
                           placeholder="请输入..." :clearable="item.editable===1||statusCode===0" type="date"
                           @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
                <div v-if="[5,10].includes(item.dataTypeID)">
                  <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                  <!-- <vxe-input  :value="getextend(data,item)" placeholder="请选择图片" readonly   class="my-search" @suffix-click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})" @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)">
                    <template #suffix >
                      <el-icon><Plus /></el-icon>
                    </template>
                  </vxe-input> -->
                  <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"
                            placeholder="请选择图片" :readonly="item.editable===0||statusCode!==0" :style="{width:(divW/3-(item.allowFixedWidth>0?item.allowFixedWidth:100)-10)+'px'}"
                            type="text" :value="getextend(data,item)">
                    <template #append>
                      <el-button class="plusA"
                                 @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:false,fileType:'images'})"
                          size="default" :icon="Plus"/>
                    </template>
                  </el-input>
                </div>
                <div v-if="item.dataTypeID===6">
                  <vxe-input v-model="data[item.fieldName]" v-show="false"></vxe-input>
                  <el-input size="default" @change="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)" :style="{width:(divW/3-(item.allowFixedWidth>0?item.allowFixedWidth:100)-10)+'px'}"
                            placeholder="请选择文件" :readonly="item.editable===0||statusCode!==0" @dblclick="showFilesImage"
                            type="text" :value="getextend(data,item)">
                    <template #append>
                      <el-button class="plusA"
                                 @click="showFiles({item:item ,value:data[item.fieldName],target:formData,ref:MT.tableName,multiple:true,fileType:'files'})"
                          size="default" >+</el-button>
                    </template>
                  </el-input>
                </div>
                <vxe-input v-if="item.dataTypeID===7" v-model="data[item.fieldName]"
                           placeholder="请输入..." :clearable="item.editable===1||statusCode===0" :readonly="item.editable===0||statusCode!==0"
                           @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
                <vxe-input v-if="item.dataTypeID===8" v-model="data[item.fieldName]" placeholder="请输入..."
                           :readonly="item.editable===0||statusCode!==0" :clearable="item.editable===1&&statusCode===0" @keyup="parseCode({event:$event,field:item,data:data})"
                           @blur="ValueChange(data,Fields[MT.tableName],item.fieldName,MT.tableName)"></vxe-input>
              </template>
                    </vxe-form-item>
                    <!-- <vxe-form-item field="Extend" :visible="false"></vxe-form-item> -->
                </vxe-form>
                <el-tabs type="border-card"  v-if=" DT.length>0">
                    <el-tab-pane :label="item.tableTitle" v-for="(item ,name) in DT" >
                        <vxe-toolbar v-show="DT.length>0&&Action.canCreate===1" size="mini" :buttons="toolbarButtons"
                                     @button-click="(value)=>buttonsClick(value,item.tableName,name)">
                        </vxe-toolbar>
                        <vxe-table border keep-source show-overflow :id="item.tableName" size="small" auto-resize :height="item.excelFormulaAutoFill===0?500:item.excelFormulaAutoFill"
                                   :edit-rules="Rules[item.tableName]" :column-config="{resizable: true}" :mouse-config='{selected: true}'
                                   :keyboard-config='{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true, isChecked: true}'
                                   :checkbox-config="{highlight: true}" :data="DetailsData[item.tableName]"
                                   :ref="el=>itemRefs[item.tableName]=el"
                                   :edit-config="{trigger: 'click', mode: 'cell',showIcon:false, showStatus: true,enabled:statusCode===0} "
                                   :show-footer="ShowFooter[item.tableName]"
                                   :footer-method="footerMethod"
                                   :tree-config="item.layoutStyle.length>0?{ transform: true,rowField: item.layoutStyle[0],parentField: item.layoutStyle[1]}:null"
                                   :expand-config="expandConfig"
                                   :cell-class-name="ErrcellClassName"
                                   :loading="tableLoad[item.tableName]"
                                   :sort-config="{defaultSort:item.Orders}"
                                   :span-method="mergeRowMethod"
                                   :row-config="{isCurrent: true, isHover: true}" @cellDblclick="showFilesImage">
                            <vxe-column type="seq" align="center" width="60"></vxe-column>
                            <vxe-column title="行号" field="Seq" align="center" :visible="false" width="60"></vxe-column>
                            <vxe-column type="expand" align="center"  width="100"
                                        v-if="Linker[item.tableName]!==undefined&&Linker[item.tableName].length>0">
                                <template #default="{ row }">
                                    <vxe-button v-for="ite in Linker[item.tableName] " status="primary" size="mini" :content="ite.title"
                                                @click="showExpand(item.tableName,row,ite.linkerID)"></vxe-button>
                                </template>
                                <template #content="{ row }">
                                    <div class="expand-wrapper">
                                        <vxe-grid :columns="expandField" :data="expandData[row.Seq]" auto-resize max-height="500"
                                                  :column-config="{resizable:true}">
                                            <template #operate="{ row ,column }">
                                                <vxe-button status="primary" size="mini" :content="column.params['button_title']"
                                                            @click="doExpand(row,Linker[item.tableName],item.tableName)"></vxe-button>
                                            </template>
                                        </vxe-grid>
                                    </div>
                                </template>
                            </vxe-column>
                            <vxe-column type="checkbox" align="center" width="40"></vxe-column>
                            <vxe-column v-for="it in Fields[item.tableName]" :field="it.fieldName"  :key="it.fieldID"
                                        :width="it.allowFixedWidth>0?it.allowFixedWidth:(item.layoutStyle[0]===it.fieldName?200:100)"
                                        :title="it.fieldDispName"
                                        :formatter="formatData"
                                        :header-align="'center'"
                                        :visible="it.hidden===0"
                                        sortable
                                        :params="{column:it}"
                                        :show-overflow="it.showRichText!==1"
                                        :tree-node="item.layoutStyle.length===0?false:item.layoutStyle[0]===it.fieldName"
                                        :edit-render="{autofocus: '.vxe-input--inner',enabled:it.editable===1}"             >
  
                                <template #header="{ column }">{{ column.title }}
                                    <vxe-button v-if="item.layoutStyle[0]===column.field" status="primary"
                                                style="height: 20px;width:40px;padding:0;" content="收展"
                                                @click="extendTree(item.tableName)"></vxe-button>
                                </template>
                                <template #edit="{ row }" >
                                    <div v-if="it.dataTypeID===1">
                                        <vxe-input v-model="row[it.fieldName]" v-show="it.componentID===0" :readonly="it.editable===0"
                                                   @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                        <el-input v-if="it.componentID>0 && [3,6].includes(it.componentType)" :value="getextend(row,it)"
                                                  v-show="it.componentID>0" placeholder="请点击选择..." readonly
                                                  @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)">
                                            <template #append>
                                                <el-button class="plusA" :disabled="it.editable===0" @click="showSource({item:it ,value:row[it.fieldName],target:row,ref:item.tableName})"
                                                           size="default">+</el-button>
                                            </template>
                                        </el-input>
                                        <vxe-select v-if="it.componentID>0 && it.componentType===1" :readonly="it.editable===0"
                                                    v-model="row[it.fieldName]" placeholder="下拉框" :clearable="item.editable===1||statusCode===0"
                                                    @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)" transfer>
                                            <vxe-option v-for="(it,index) in Combo[it.fieldName]" :value="it.value" :label="it.label"
                                                        :key="index"></vxe-option>
                                        </vxe-select>
                                        <vxe-input v-if="it.componentID>0 && it.componentType===5" v-model="row[it.fieldName]"
                                                   :readonly="it.editable===0" placeholder="自动取得编号"
                                                   @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)">
                                        </vxe-input>
                                    </div>
                                    <vxe-input v-if="it.dataTypeID===2" v-model="row[it.fieldName]" placeholder="请输入..."
                                               :readonly="it.editable===0" type="integer"
                                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                    <vxe-input v-if="it.dataTypeID===3" v-model="row[it.fieldName]" placeholder="请输入..." autoselect
                                               :readonly="it.editable===0" type="float" :digits="it.fieldPrecision"
                                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                    <vxe-input v-if="it.dataTypeID===4" v-model="row[it.fieldName]" placeholder="请输入..."
                                               :readonly="it.editable===0" transfer :clearable="item.editable===1||statusCode===0" type="date"
                                               @change="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                    <div v-if="[5,10].includes(it.dataTypeID)">
                                        <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
                                        <vxe-input :value="getextend(row,it)" placeholder="请选择图片" readonly class="my-search"
                                                   @suffix-click="showFiles({item:it ,value:row[it.fieldName],target:row,ref:item.tableName,multiple:false,fileType:'images'})"
                                                   @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)">
                                            <template #suffix>
                                                <el-icon>
                                                    <Plus/>
                                                </el-icon>
                                            </template>
                                        </vxe-input>
                                    </div>
                                    <div v-if="it.dataTypeID===6">
                                        <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
                                        <el-input size="default" @change="ValueChange(row,Fields[it.tableName],it.fieldName,it.tableName)"
                                                  placeholder="请选择文件" :readonly="it.editable===0||statusCode!==0" :style="{width:(divW/3-(item.allowFixedWidth>0?item.allowFixedWidth:100)-10)+'px'}"
                                                  type="text" :value="getextend(row,it)">
                                            <template #append>
                                                <el-button :disabled="it.editable===0" class="plusA"
                                                           @click="showFiles({item:it ,value:row[it.fieldName],target:row,ref:item.tableName,multiple:true,fileType:'files'})"
                                                           size="default" >+</el-button>
                                            </template>
                                        </el-input>
                                    </div>
                                    <vxe-input v-if="it.dataTypeID===7" v-model="row[it.fieldName]" placeholder="请输入..."
                                               :readonly="it.editable===0" :clearable="item.editable===1||statusCode===0"
                                               @blur="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                    <vxe-input v-if="it.dataTypeID===8" v-model="row[it.fieldName]" placeholder="请输入..."
                                               :readonly="it.editable===0" :clearable="item.editable===1||statusCode===0"
                                               @change="ValueChange(row,Fields[item.tableName],it.fieldName,item.tableName)"></vxe-input>
                                </template>
                            </vxe-column>
                            <vxe-column title="操作" :fixed="!isequipment?'':'right'" width="230" v-if="item.layoutStyle.length>0&&statusCode===0">
                                <template #default="{ row }">
                                    <vxe-button type="text" status="primary" icon="fa fa-cube" @click="insertTreeRow(item,row, 'current')">
                                        平级
                                    </vxe-button>
                                    <vxe-button type="text" status="primary" icon="fa fa-cubes" @click="insertTreeRow(item,row, 'bottom')">
                                        下级
                                    </vxe-button>
                                    <vxe-button type="text" status="primary" icon="fa fa-trash-o" @click="deleteTreeRow(item,row)"
                                                v-if="candelete(item,row)">删除
                                    </vxe-button>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        <div v-if="[2,5].includes(Template.allowBestFitColumns)&&formData.StatusCode>0" style="min-width:300px;max-width:300px;border: 1px dashed green;padding: 10px;  display: inline-block;">
  
        <div :style="{height: ApprovalData.do?'550px':'100%',maxHeight:'600px',overflow: 'scroll'}">
            <sxPse :data="ApprovalData.tasks"></sxPse>
        </div>
        <div v-if="ApprovalData.do">
            <vxe-form
                       title-colon
                       ref="FLForm"
                       title-width="100"
                       :data="fldata"
                       :rules="ApprovalRules"
                       @submit="FLsubmitEvent">
                <vxe-form-gather span="24" v-if="!fldata.start">
                <vxe-form-item field="status" :item-render="{}"  style="width: 120px">
                    <template #default="{ data }">
                        <vxe-radio-group v-model="data.status" @click="approstatus" style="width: 120px">
                            <vxe-radio :label="8" content="同意"></vxe-radio>
                            <vxe-radio :label="7" content="退回"></vxe-radio>
                        </vxe-radio-group>
                    </template>
                </vxe-form-item>
                <vxe-form-item field="back" :item-render="{}" style="width: 90px;margin-left: 10px" >
                    <template #default="{ data }">
                        <vxe-select v-model="data.back"  :disabled="fldata.status!==7" placeholder="选择退回" size="mini" style="width: 90px;margin-left: 10px" >
                            <vxe-optgroup label="常用">
                                <vxe-option  label="退回上一步" value="one"> </vxe-option>
                                <vxe-option  label="退回发起人" value="home"> </vxe-option>
  
                            </vxe-optgroup>
                            <vxe-optgroup label="已审批节点">
                                <vxe-option
                                        v-for="(item,index) in ApprovalData.history"
                                        :key="index"
                                        :label="item.title"
                                        :value="item.node">
                                </vxe-option>
                            </vxe-optgroup>
                        </vxe-select>
  
                    </template>
                </vxe-form-item>
  
                <vxe-form-item field="opinion" span="24" :item-render="{}" v-if="!fldata.start" >
                    <template #default="{ data }">
                        <vxe-textarea v-model="data.opinion" placeholder="请输入审批意见" :autosize="{minRows: 3, maxRows: 3}" clearable></vxe-textarea>
                    </template>
                </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-item align="center" span="24">
                    <template #default="{ data }">
                        <vxe-button status="primary" :disabled="data.status!==8 " @click="addproc()" content="加签"></vxe-button>
                        <vxe-button type="submit" status="primary" content="提交"></vxe-button>
                        <vxe-button type="reset" content="重置"></vxe-button>
                    </template>
                </vxe-form-item>
            </vxe-form>
        </div>
    </div>
  
  
  
  
  
      <DataGridSelect ref="DGE" :isequipment="isequipment" @submit="getSourceData"></DataGridSelect>
      <FilesSelect ref="Files" :isequipment="isequipment" @submit="getFilesData"></FilesSelect>
      <print ref="Print"></print>
      <organization ref="Organization" @selectUser="addsign"></organization>
      <print3view ref="print3viewRef"/>
    </div>
  </template>
  
  <script>
  import {getCurrentInstance, onMounted, reactive, ref, toRefs, watch} from "vue"
  import XEUtils from 'xe-utils'
  import {ElMessage, ElMessageBox} from 'element-plus'
  import {
      formCheck,
      getDefault,
      getdingfileid,
      getfilter,
      getForm,
      getSelectRule,
      loadExpand,
      rePost, reSendmsg,
      RunExpand,
      updateRule,
      uploaddingfileid
  } from "/@/api/linkoo/form/index"
  import {useRoute, useRouter} from 'vue-router'
  import {Plus} from '@element-plus/icons-vue'
  import {editForm} from "/@/api/linkoo/form"
  import DataGridSelect from './select.vue'
  import organization from './organization.vue'
  import FilesSelect from './FilesSelect.vue'
  import {mathAll} from "/@/utils/mathji"
  import {useStore} from '/@/store';
  import {getCode, getDingTalksCheck} from '/@/api/login'
  import {flowTodo,getWorkFlowData} from "/@/api/linkoo/workflow";
  import sxPse from "./sxpse.vue"
  import Postlog from "../components/postlogs.vue"
  import print from "/@/views/linkoo/print/typrint.vue"
  import print3view from "/@/views/linkoo/print/print3view.vue"
  import {getPrintList} from "/@/api/linkoo/print";
  import {GetPrintFormat} from "/@/views/linkoo/print/toPrintContent";
  
  export default {
    props: ['Fieldss', 'MT', 'DT', 'Combo', 'isequipment', 'Rules', 'ActRules', 'Action','isNew', 'Template', 'DataSource', 'load', 'Linker','alltable'],
    components: {DataGridSelect,print3view, FilesSelect,sxPse,print,organization},
    setup(props, ctx) {
      const {proxy} = getCurrentInstance()
      let Print = ref()
      let rq = ref()
      let Organization = ref()
      let FLForm = ref()
      let DGE = ref(null)
      let Files = ref(null)
      let refForm = ref(null)
      let print3viewRef = ref(null)
      let router = useRouter()
      let store = useStore()
      const route = useRoute()
      let state = reactive({
        opinion:{8:'同意',7:'退回',9:'拒绝'},
        statusCode:0,
        RecordID: 0,
        formData: {},
        validateCheck: true,
          canPrint: false,
        OldMData: {},
        OldDData: {},
        selectMainData: {},
        printTemplates: [],
        DetailsData: {},
        selectTab: null,
        tableHeight: {},
        resize: '',
        template: {},
        AllData: {},
        firstload: true,
        linker: {},
        ManualActRules: {},
        tableLoad: {},
        rid: route.params.id,
        itemRefs: {},fldata:{},
        toolbarButtons: [
          {code: 'add', name: '新增'}, {code: 'copy', name: '复制'}, {code: 'clear', name: '清空'}, {
            code: 'delete',
            name: '删除'
          },  { name: '其它',  dropdowns: [
              { code: 'showSeq', name: '显示行号', type: 'text', },
              { code: 'test', name: '测试', type: 'text', },
            ]}
        ],
        mergeCellField:[],
        selectDataGridTarget: {},
        selectFiels: {},
        ApprovalData: {tasks:[],history:[]},
        ApprovalRules: {status: [
                { required: true, message: '请选择审批意见' },
            ],},
        ShowFooter: {},
        FooterFields: {},
        expandcfg: {},
        DataSource: {},
        expandField: [],
        Fields: [],
        expandData: {},
        expandrow: {},
        parentV: '',
        hjfield: [],
        filters:{},
        ismain: false,
        TreeExpand: false,
        wkedit: false,
        wkeditls: false,
        canEdit:false,
        showedit:false,
        DFV:{}, divW:0,
        workFlowWidth:3,
        expandConfig: {
          accordion:true,
          lazy: true,
          loadMethod({row}) {
            return new Promise(resolve => {
              loadExpand(state.expandcfg).then(res => {
                state.expandField = res.data.field
                state.expandData[row.Seq] = res.data.list
                resolve()
              })
            })
          },
          visibleMethod() {
            return false
          }
        },
      })
      watch(props, (ovl, evl) => {
        if (props.load && state.firstload) {
            state.firstload = false
          Load(1)
        }
      })
        window.onresize = () => {
            return (() => {
                resizeWidth()
            })()
        }
        const resizeWidth=()=>{
            state.divW=proxy.$refs.rq.clientWidth-([2,5].includes(props.Template.allowBestFitColumns)&&state.formData.StatusCode>0?260:0)
        }
      const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
        const fields = state.mergeCellField
        const cellValue = row[column.field]
        if (cellValue && fields.includes(column.field)) {
          const prevRow = visibleData[_rowIndex - 1]
          let nextRow = visibleData[_rowIndex + 1]
          if (prevRow && prevRow[column.field] === cellValue) {
            return { rowspan: 0, colspan: 0 }
          } else {
            let countRowspan = 1
            while (nextRow && nextRow[column.field] === cellValue) {
              nextRow = visibleData[++countRowspan + _rowIndex]
            }
            if (countRowspan > 1) {
              return { rowspan: countRowspan, colspan: 1 }
            }
          }
        }
      }
      const Load = (type) => {
        let AllData = {}
        if (type === 1) {
          AllData = props.DataSource
        } else {
          AllData = state.AllData
        }
  
            // return
        XEUtils.arrayEach(props.DT, row => {
          state.ShowFooter[row.tableName] = false
          state.FooterFields[row.tableName]=[]
        })
        // if (props.DataSource[props.MT.tableName]) {
        state.OldMData = XEUtils.omit(AllData, 'ChildTables')
        state.formData = XEUtils.omit(AllData, 'ChildTables')
        state.Fields = XEUtils.clone(props.Fieldss, true)
        state.RecordID = state.formData.RecordID
        state.canEdit = props.Action.canReview>0&&![1, 2,8].includes(state.formData.StatusCode)
        // }
        if (AllData.ChildTables) {
          state.OldDData = XEUtils.clone(AllData.ChildTables, true)
          state.DetailsData = XEUtils.clone(AllData.ChildTables, true)
        }
        props.DT.forEach(row => {
          state.tableLoad[row.tableName]=false
          state.DFV[row.tableName]={RecordID: state.RecordID, Seq: null, Extend: '{}'}
          state.mergeCellField.push(...XEUtils.map(row.Fields.filter(item=>item.showCalendar===1),item=>item.fieldName))
          state.tableHeight[row.tableName] = document.documentElement.clientHeight-((state.Fields[row.tableName].filter(item=>item.hidden===0).length)*45)
          if (row.layoutStyle.length > 0 && row.onSheet.length > 0) {
            state.hjfield = state.hjfield.concat(row.onSheet)
          }
          const ff=row['onSheet'].toString()!==''?row['onSheet'].toString().split(','):[]
          if(ff.length>0){
            state.FooterFields[row.tableName]=state.FooterFields[row.tableName].concat(ff)
            state.ShowFooter[row.tableName]=true
          }
          XEUtils.objectEach(row.Fields,  (f, key) => {
                  state.DFV[row.tableName][f['fieldName']] = null
            })
  
        })
        XEUtils.objectEach(props.ActRules, async (items, key) => {
          let rules = XEUtils.filter(items, item => item.runTime.split(',').includes('999'))
          if (rules.length > 0) {
            state.ManualActRules[key] = rules
          }
        })
        if (props.isNew && type === 1 ) {
          state.statusCode=0
          state.RecordID = 0
          state.showedit=true
          //console.log(state.formData, props.MT.tableID);
          getDefaults(state.formData, props.MT.tableID)
        }
          state.canPrint=props.Action.canPrint===1
          state.canEdit=props.Action.canReview===1
  
        if([2,5].includes(props.Template.allowBestFitColumns)&&state.formData.StatusCode>0){
          state.workFlowWidth=store.state.themeConfig.themeConfig.workFlowWidth?store.state.themeConfig.themeConfig.workFlowWidth:4
          GetWF()
        }
          state.divW=proxy.$refs.rq.clientWidth-([2,5].includes(props.Template.allowBestFitColumns)&&state.formData.StatusCode>0?260:0)
        doedit()
        getPrintList({tid:props.MT.templateID}).then(res=>{
            state.printTemplates=res.data.list||[]
            state.ismain=res.data.pv===1
        })
      }
      const GetWF=()=>{
        getWorkFlowData(props.Template.templateCode,state.formData.RecordID).then(res=>{
          if (res.data.tasks!==undefined&&res.data.tasks.length>0){
              state.divW=proxy.$refs.rq.clientWidth-([2,5].includes(props.Template.allowBestFitColumns)&&state.formData.StatusCode>0?260:0)
            state.ApprovalData=res.data
              state.showedit=false
              // state.fldata.status=1
              state.fldata.start=false
              if(res.data.start!==undefined && res.data.start){
                  state.fldata.start=res.data.start
                  state.showedit=true
                  state.wkeditls=true
              }
              state.fldata.TaskNode=res.data.tasknode
              state.fldata.TlID=res.data.tlid
              state.fldata.RID=state.formData.RecordID
              state.fldata.TCode=props.Template.templateCode
              state.ApprovalData.history=[]
              XEUtils.arrayEach(  XEUtils.orderBy(res.data.tasks, 'createTime'),(item,index)=>{
                  if (item.status===8&&XEUtils.find(state.ApprovalData.history,it=>it.node===item.taskNode)===null){
                      state.ApprovalData.history.push({node:item.taskNode,title:item.taskName})
                  }
              })
              if(res.data.fillField&&res.data.fillField.length>0){
                  state.showedit=true
                  state.statusCode=0
                  state.canEdit=true
                  XEUtils.objectEach(state.Fields,(fidlds,tb)=>{
                      fidlds=fidlds.map(f=>{
                          if(res.data.fillField.includes(f.fieldName)){
                              f.editable=1
                              props.Rules[tb][f.fieldName]=[{"message": f.fieldDispName+"必填填写","required": true},{"trigger": "manual"}]
                          }else {
                              f.editable=0
                          }
                          return f
                      })
                  })
                  doedit()
              }
  
  
          }
  
        })
      }
  
      const getDefaults = (target, id) => {
        getDefault(id).then(res => {
          XEUtils.objectEach(res.data, (item, key) => {
            target[key] = item
          })
          if (id === props.MT.tableID) {
            target['StatusCode'] = 0
          }
        })
        XEUtils.objectEach(props.ActRules, async (items) => {
          let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('101') || item.runTime.split(',').includes('102'))
          for (let i = 0; i < selectrules.length; i++) {
            await loadSelectRules(selectrules[i])
          }
        })
      }
      const runActRules = (rule) => {
       // ElMessage.success('执行程序中....'+rule.ruleName)
        switch (rule.ruleType) {
          case 1:
            loadSelectRules(rule)
            break
          case 2:
            runUpdateRule(rule)
            break
          case 3:
            runPostRule(rule)
            break
          case 4:
            runSendMsg(rule)
            break
  
        }
      }
      const runSendMsg = async (rule) => {
         // console.log(rule)
          reSendmsg(state.formData.RecordID, rule.ruleID)
      }
        const runPostRule = async (rule) => {
        if (rule.isExtFlow === 1 && rule.sourceType === 1 ) {
          if((state.statusCode===99&&[1,2,8].includes(state.formData.StatusCode))||[1,2,8].includes(state.formData.StatusCode)){
            ElMessage.error('单据状态已变更,不允许再次提交!')
            return
          }
          let files = [], corpId = '', kk = getDingTalksCheck()
          await getdingfileid(rule.ruleID, state.formData.RecordID).then(async res => {
            files = res.data['fileId'] || [];
            corpId = res.data.corpId;
          })
          if (files.length > 0) {
            if (!kk) {
              ElMessage.error('有附件需要在钉钉客户端环境中上传,请在钉钉客户端中重试!')
              return
            } else {
              ElMessage.info('开始传送钉钉表单')
              let sendFiles = files.length
              for (let i = 0; i < files.length; i++) {
                await getCode(corpId, async (code) => {
                  //  this.dingCode=code
                  if (!code) {
                    ElMessage.error('未取得钉钉用户code')
                    // this.sendingLoading = false
                    return
                  }
                  await uploaddingfileid(files[i], code).then(res => {
                    ElMessage.success(res.message)
                    sendFiles--
                    if (sendFiles === 0) {
                      ElMessage.success("附件上传完毕!")
                      dopotrule(rule)
                    }
                  })
                })
              }
            }
          } else {
            dopotrule(rule)
          }
  
        } else {
          dopotrule(rule)
        }
  
      }
      const dopotrule = (rule) => {
        rePost(state.formData.RecordID, rule.ruleID).then(res => {
          if (res.code === 0) {
            if (rule.isExtFlow === 1 && rule.sourceType === 1 ){
              state.statusCode=1
            }
            ElMessage.success('成功执行[' + rule.ruleName + ']')
          }
        })
      }
      const runUpdateRule = (rule) => {
        let filterExpr = rule.sqlSchema
        const regex = /({(\S+)[.](\S+)})/gis
        let m
        let keys = [], table = [], vals = []
        while ((m = regex.exec(filterExpr)) !== null) {
          // 这对于避免零宽度匹配的无限循环是必要的
          if (m.index === regex.lastIndex) {
            regex.lastIndex++
          }
          m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
              keys.push(match)
            }
            if (groupIndex === 2) {
              table.push(match)
            }
            if (groupIndex === 3) {
              vals.push(match)
            }
          })
        }
        XEUtils.arrayEach(keys, (it, key) => {
          if (table[key] !== props.MT.tableName && XEUtils.filter(props.DT, item => item.tableName === table[key])) {
            const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[key].getTableData().fullData, true), vals[key])
            filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
          } else {
            let val = XEUtils.get(state.formData, vals[key], "''")
            filterExpr = filterExpr.replace(it, val)
            filterExpr = filterExpr.replace('@RecordID', route.params.id.toString())
          }
        })
        updateRule(rule.ruleID, filterExpr, state.formData.RecordID).then(res => {
          if (res.code === 0) {
            ElMessage.success('成功执行[' + rule.ruleName + ']')
          }
        })
      }
      const loadSelectRules = async (rule) => {
        ElMessage.info('开始执行取数....')
        if (rule.ruleName === '合计') {
          const r = XEUtils.toStringJSON(rule.targetField)
          r.forEach(row => {
            const t = row.tofield.split('.')
            const f = row.field.split('.')
            if (t[0] === props.MT.tableName) {
              if (props.isequipment) {
                const $tb = state.itemRefs[f[0]]
                state.formData[t[1]] = XEUtils.sum($tb.getTableData().visibleData, f[1])
              } else {
                state.formData[t[1]] = XEUtils.sum(state.DetailsData[f[0]], f[1])
              }
            } else {
            }
          })
          return
        }
        let filterExpr = rule.filterExpr
        const regex = /({([a-zA-Z\d]+)[.]([a-zA-Z\d]+)})/gis
        let m
        let keys = [], table = [], vals = []
        while ((m = regex.exec(filterExpr)) !== null) {
          // 这对于避免零宽度匹配的无限循环是必要的
          if (m.index === regex.lastIndex) {
            regex.lastIndex++
          }
          m.forEach((match, groupIndex) => {
            if (groupIndex === 1) {
              keys.push(match)
            }
            if (groupIndex === 2) {
              table.push(match)
            }
            if (groupIndex === 3) {
              vals.push(match)
            }
          })
        }
        XEUtils.arrayEach(keys, (it, key) => {
            let data={}
          if (table[key] !== props.MT.tableName && filterExpr.indexOf(' in ') > 1) {
            const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[table[key]].getTableData().fullData, true), vals[key])
            filterExpr = filterExpr.replace(it, `'${data.join("','")}'`)
          } else {
            let val = XEUtils.get(state.formData, vals[key], '')
            if (val.length === 0&&state.itemRefs[table[key]]!==undefined) {
              const data = state.itemRefs[table[key]].getCurrentRecord()
              val = XEUtils.get(data, vals[key], "")
            }
  
            filterExpr = filterExpr.replace(it, val)
          }
        })
        await GetSelectRules(rule, filterExpr)
      }
      const GetSelectRules = async (rule, filterExpr) => {
        await getSelectRule(rule.ruleID, filterExpr).then(res => {
          if (res.data.list) {
            fromSelectRule(rule, res.data.list)
            ElMessage.success('成功执行[' + rule.ruleName + '],数据已添加')
          } else {
            ElMessage({type: 'info', message: '成功执行[' + rule.ruleName + '],但未到取到数据',})
          }
        })
      }
      const fromSelectRule =  (rule, data) => {
        if (data === null) return
  
        const topull = JSON.parse(rule['targetField'])
        const op = JSON.parse(rule['sendInfo'])
          let getdef=op['getDefault']===undefined?true:op['getDefault']===1
  
        let TB = {}, link = false, linkstr = []
        topull.forEach(row => {
          const tf = row['tofield'].split('.')
          if (TB[tf[0]] === undefined) TB[tf[0]] = {}
          TB[tf[0]][tf[1]] = row['field'].indexOf('.') > -1 ? row['field'].split('.')[1] : row['field']
          if (row.type === 'keys') {
            link = true
            linkstr.push(tf[1])
          }
        })
        XEUtils.objectEach(TB, async (fields, key) => {
          if (key === props.MT.tableName) {
            XEUtils.objectEach(fields, (f, t) => {
              state.formData[t] = data[0][f]
            })
          } else {
            state.tableLoad[key]=true
            const $tb = state.itemRefs[key]
            let records = []
            for (let i=0;i<data.length;i++){
  
              const record = await getDTdefault(key,getdef)
              XEUtils.objectEach(fields, (f, t) => {
                record[t] = data[i][f]
              })
                XEUtils.objectEach(state.Fields[key], (field) => {
                    if (field.componentType === 9 && field.componentFieldName !== '') {
                        record[field.fieldName] = mathAlls(field, record)
                    }
                })
                await getDefault(160).then(res => {
                  XEUtils.objectEach(res.data, (item, key) => {
                    record[key] = item
                  })
                })
              records.push(record)
            }
            if (rule.clearAllRow === 1) {
              $tb.remove()
            }
            if (link) {
              const $tb = state.itemRefs[key]
              let dd =  $tb.getTableData().visibleData
  
              XEUtils.mapTree(dd, item => {
                  let Ls=records
                  XEUtils.arrayEach(linkstr,lk=>{
                      Ls = XEUtils.filter(Ls, r => r[lk] === item[lk])
                  })
                if (Ls.length>0) {
                    XEUtils.arrayEach(Ls,record=>{
                        XEUtils.objectEach(record, (it, key) => {
                            if(it){
                                item[key] = it
                            }
                        })
                    })
  
                }
                XEUtils.objectEach(state.Fields[key], async (field) => {
                  if (field.componentType === 9 && field.componentFieldName !== '') {
                    item[field.fieldName] = mathAlls(field, item)
                  }
                })
                return item
              })
              $tb.updateData(dd)
              setTimeout(()=>{
                 getDFSum(key)
              },200)
                await $tb.validate()
            } else {
              if($tb.treeConfig){
                records=XEUtils.toArrayTree(records,{parentKey:$tb.treeConfig.parentField,key:$tb.treeConfig.rowField})
                records=XEUtils.toTreeArray(records,{clear:true})
                for(let i=0;i<records.length;i++){
                  await $tb.insertAt(records[i])
                }
              }else{
                $tb.insertAt(records,-1)
              }
  
            }
            state.resize = key
            state.tableLoad[key]=false
          }
        })
      }
      //自上而下进行数量累计计算
      const updateTreeDataAdd = (treeData, fieldNameArray,maths) => {
        for (let i = 0; i < treeData.length; i++) {
          //只有存在子集时，才进行累加计算，否则不修改自身属性值
          if (treeData[i].children && treeData[i].children.length > 0) {
            //递归遍历并修改children的对应值
            treeData[i].children = updateTreeDataAdd(treeData[i].children, fieldNameArray,maths);
            // for (let k = 0; k < fieldNameArray.length; k++) {
            //   let fieldName = fieldNameArray[k];
              let addSum = 0.00;
              //循环相加计算和
              for (let j = 0; j < treeData[i].children.length; j++) {
                let childNum = treeData[i].children[j][fieldNameArray[1]];
                addSum += XEUtils.toNumber(childNum);
                //赋值
                treeData[i][fieldNameArray[0]] = XEUtils.toFixed(addSum, 2);
              }
            // }
            for (let field in maths)
            {
              treeData[i][field]=mathAll(maths[field], treeData[i])
            }
          }
        }
        return treeData;
      }
        const ErrcellClassName = ({ row, column }) => {
            if (column.field === 'F878'&& row['F787']==='重复') {
                console.log(column)
            }
            return null
        }
      const getDFSum = async (table) => {
        const $tb = state.itemRefs[table]
        await $tb.setAllTreeExpand(true)
        const tb = XEUtils.find(props.DT, item => item.tableName === table)
        $tb.updateData( updateTreeDataAdd($tb.getTableData().visibleData,tb.onSheet,tb.TreeSum))
      }
      const getextend = (data, field) => {
        //  console.log(data,field);
        let extend = XEUtils.toStringJSON(data['Extend'] ? data['Extend'] : '{}')
        if (extend[field.fieldName] === undefined) {
          extend[field.fieldName] = data[field.fieldName]
          //  console.log(data,extend,field.fieldName,"1234567890987654321");
          data['Extend'] = XEUtils.toJSONString(extend)
        }
        // console.log(XEUtils.get(extend,field.fieldName),"pppppp");
        return field.dataTypeID!==6?data[field.fieldName]:extend[field.fieldName]
      }
      const ValueChange = async (data, fields, fieldName, tableName) => {
  
        let source = XEUtils.clone(data)
        let extend = XEUtils.toStringJSON(data['Extend'])
        source = XEUtils.objectMap(source, item => item === null ? 0 : item)
        XEUtils.objectEach(fields, async (field) => {
          if (field.componentType === 9 && field.componentFieldName !== ''&& field.fieldName!==fieldName) {
            data[field.fieldName] = mathAlls(field, source)
            if (state.hjfield.includes(field.fieldName)) {
              await getDFSum(tableName)
            }
          }
  
          if (field.dataTypeID !== 6 && field.componentType === 0 && extend[field.fieldName] !== null && extend[field.fieldName] !== undefined) {
            extend[field.fieldName] = data[field.fieldName]
          }
        })
        data['Extend'] = JSON.stringify(extend)
  
        setTimeout(async ()=>{XEUtils.objectEach(props.ActRules, async (items) => {
          let selectrules = XEUtils.filter(items, item => item.runTime.split(',').includes('106') && XEUtils.includes(item['onChangeFileld'].split(','), fieldName))
          for (let i = 0; i < selectrules.length; i++) {
            await loadSelectRules(selectrules[i])
          }
        })
          if (state.hjfield.includes(fieldName)) {
            await getDFSum(tableName)
          }
        },200)
  
  
  
      }
      const formatData = ({cellValue, row, column}) => {
        let extend = XEUtils.toStringJSON(row['Extend'])
        if (extend[column.field] === null || extend[column.field] === undefined) {
          extend[column.field] = cellValue ? cellValue : ''
        }
        return XEUtils.get(extend, column.field)
      }
      const deleteTreeRow = async (table, row) => {
        const $table = state.itemRefs[table.tableName]
        await $table.remove(row)
      }
      const candelete = (table, row) => {
        const $table = state.itemRefs[table.tableName]
        const data = $table.getData()
        return !data.filter(item => item[table.layoutStyle[1]] === row[table.layoutStyle[0]]).length > 0
      }
      const insertTreeRow = async (table, currRow, locat) => {
        const $table = state.itemRefs[table.tableName]
        let record = await getDTdefault(table.tableName,true)
        XEUtils.objectEach(state.Fields[table.tableName], (item, key) => {
          if (item.componentType === 9 && item.componentFieldName !== '') {
            record[item.fieldName] = mathAlls(item, record)
          }
        })
        if (locat === 'current') {
          record[table.layoutStyle[1]] = currRow[table.layoutStyle[1]]
          state.parentV = currRow[table.layoutStyle[1]]
          const {row: newRow} = await $table.insertAt(record, -1)
          await $table.setEditRow(newRow) // 插入子节点
        } else if (locat === 'top') {
          record[table.layoutStyle[1]] = currRow[table.layoutStyle[0]]
          state.parentV = currRow[table.layoutStyle[0]]
          const {row: newRow} = await $table.insert(record)
          await $table.setTreeExpand(currRow, true) // 将父节点展开
          await $table.setEditRow(newRow) // 插入子节点
        } else if (locat === 'bottom') {
          record[table.layoutStyle[1]] = currRow[table.layoutStyle[0]]
          state.parentV = currRow[table.layoutStyle[0]]
          const {row: newRow} = await $table.insertAt(record, -1)
          await $table.setTreeExpand(currRow, true) // 将父节点展开
          await $table.setEditRow(newRow) // 插入子节点
        }
      }
      // const treeTotalSUM = async (fieldName, data) => {
      //   XEUtils.arrayEach(props.DT, async (table, index) => {
      //     if (table.layoutStyle.length > 0 && table.onSheet.includes(fieldName)) {
      //       const $tb = state.itemRefs[table.tableName]
      //       const datas = $tb.getTableData().tableData
      //       const pv = data[table.layoutStyle[1]]
      //       const P = XEUtils.findTree(datas, item => item[table.layoutStyle[0]] === pv)
      //       if (P !== undefined) {
      //         P.item[fieldName] = XEUtils.sum(P.item.children, fieldName)
      //         XEUtils.objectEach(state.Fields[table.tableName], (item, key) => {
      //           if (item.componentType === 9 && item.componentFieldName !== '' && !table.onSheet.includes(fieldName)) {
      //             const jgm = mathAll(item.componentFieldName, P.item)
      //             P.item[item.fieldName] = jgm ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
      //           }
      //         })
      //         if (P.item[table.layoutStyle[1]] !== '') {
      //           await treeTotalSUM(fieldName, P.item)
      //         }
      //       }
      //     }
      //   })
      // }
      const getDTdefault = async (table,news) => {
        const row = state.DFV[table]
          const tb = XEUtils.find(props.DT, item => item.tableName === table)
          if(tb.allowWorkFlow>0&&news){
          await getDefault(tb.tableID).then(res => {
            XEUtils.objectEach(res.data, (item, key) => {
              row[key] = item
            })
          })
        }
  
        return XEUtils.clone(row)
      }
      const buttonsClick = async ({code, button, $event}, name, index) => {
        if(state.statusCode!==0) {
        ElMessage.info("查看模式,操作无效")
          return
        }
        state.selectTab = name
        switch (code) {
          case 'add': {
            let target = await getDTdefault(name,true)
            XEUtils.objectEach(state.Fields[name], (item, key) => {
              if (item.componentType === 9 && item.componentFieldName !== '') {
                target[item.fieldName] = mathAlls(item, target)
              }
            })
            const {row: fnewRow} = await state.itemRefs[name].insertAt(target, -1)
            await state.itemRefs[name].setActiveCell(fnewRow, state.Fields[state.selectTab][0]['fieldName'])
            await state.itemRefs[name].setCurrentRow(fnewRow)
            // this.tableHeight[this.selectTab]=this.tableHeight[this.selectTab]>500?this.tableHeight[this.selectTab]:this.tableHeight[this.selectTab]+40
            state.resize = fnewRow['_X_ID']
            break
          }
          case 'delete': {
            const Fieldrows = state.itemRefs[name].getCheckboxRecords()
            if (Fieldrows.length > 0) {
              ElMessageBox.confirm("您确定要删除该数据?", "警告", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              }).then(() => {
                state.resize = Fieldrows[0]['_X_ID']
                state.itemRefs[name].remove(Fieldrows)
              })
            } else {
              ElMessage({type: 'info', message: '选择数据后再删除!',})
            }
            break
          }
          case 'clear': {
            ElMessageBox.confirm("您确定要清空数据吗?", "警告", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              state.itemRefs[name].remove()
            })
            break
          }
          case 'showSeq': {
            const field=state.itemRefs[name].getColumnByField("Seq")
            field.visible=!field.visible
            state.itemRefs[name].refreshColumn()
            break
          }
          case 'test': {
            // console.log('getData()',state.itemRefs[name].getData())
            // console.log('getTableData().fullData',state.itemRefs[name].getTableData().fullData)
            // console.log('getTableData().tableData',state.itemRefs[name].getTableData().tableData)
            // getDTDataSum(state.itemRefs[name].getTableData().tableData, XEUtils.find(props.DT, item => item.tableName === name))
            getDFSum(name)
            break
          }
          case 'copy': {
            const Fieldrows = state.itemRefs[name].getCheckboxRecords()
            if (Fieldrows.length > 0) {
              const fields = Fieldrows.map((row, index) => {
                row['RecordID'] = state.RecordID;
                row['Seq'] = null;
                row['Extend'] = '{}';
  
                delete row['_X_ROW_KEY'];
                return row
              })
              await state.itemRefs[name].insertAt(fields, -1)
              // this.tableHeight[this.selectTab]=40*Fieldrows.length+120>500?500:this.tableHeight[this.selectTab]+40*Fieldrows.length
            } else {
              ElMessage({
                type: 'info',
                message: '选择数据后再复制!',
              })
            }
            break
          }
        }
      }
      const extendTree = async (name) => {
        state.TreeExpand = !state.TreeExpand
        if (state.TreeExpand) {
          await state.itemRefs[name].setAllTreeExpand(state.TreeExpand)
        } else {
          await state.itemRefs[name].clearTreeExpand()
          state.itemRefs[name].updateFooter()
        }
      }
      const getAutoCode = (fields, target, field) => {
        if (field) {
          field = XEUtils.find(fields, item => item.fieldName === field)
          if (field.componentType === 5 && target[field.fieldName] !== '') {
            ElMessageBox.confirm("是否确认重新获取编号?", "警告", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              ElMessage({
                type: 'info',
                message: '确认重新获取编号',
              })
              // getAutoCodes(this.$route.name,field.componentID).then(res=>{
              //     target[field.fieldName]=res.data
              // })
            }).catch(function () {
            });
          }
        } else {
          XEUtils.objectEach(fields, (item, key) => {
            if (item.default !== '') {
              target[item.fieldName] = item.default
            }
            if (item.componentType === 5 && XEUtils.toValueString(target[item.fieldName]) === '') {
              // getAutoCodes(this.$route.name,item.componentID).then(res=>{
              //     target[item.fieldName]=res.data
              // })
            }
          })
        }
      }
      const showSource = async ({item, value, target, ref}) => {
       // console.log(item, value, target, ref);
        if(state.statusCode!==0)return
        if (item.componentFilterExpr !== '' && item.componentType === 3) {
          if (state.filters[item.fieldName]===undefined){
            state.filters[item.fieldName]=XEUtils.clone(item.componentFilterExpr, true)
          }
          let filter = XEUtils.clone( state.filters[item.fieldName], true)
            const regex = /({(\S+)})/gis
            let m
            let keys = [], vals = []
            while ((m = regex.exec(filter)) !== null) {
              // 这对于避免零宽度匹配的无限循环是必要的
              if (m.index === regex.lastIndex) {
                regex.lastIndex++
              }
              // 结果可以通过`m变量`访问。
              m.forEach((match, groupIndex) => {
                if (groupIndex === 1) {
                  keys.push(match)
                }
                if (groupIndex === 2) {
                  vals.push(match)
                }
              })
            }
            XEUtils.arrayEach(keys, (it, key) => {
              //   // 主字段查找
              let val = XEUtils.get(state.formData, vals[key], '')
              if (val === '') {
                //     // 明细表行数据查找
                val = XEUtils.get(target, vals[key], '')
              }
              if (filter.indexOf(' in ') > 1) {
                const data = XEUtils.pluck(XEUtils.clone(state.itemRefs[ref].getTableData().fullData, true), vals[key])
               // console.log(data,'dddddd')
                let vv=data?data.join("','"):''
                filter = filter.replace(it, `'${vv}'`)
              }else{
                filter = filter.replace(it, val)
              }
            })
  
          item.componentFilterExpr = filter
        }
        DGE.value.Data = Object.assign({}, {field: item, value: value, data: state.formData})
        DGE.value.todo(item.expandType)
        DGE.value.keyword=''
        // this.$refs.DGE.showDialog = true
        state.selectDataGridTarget = {field: item, target: target, ref: ref}
      }
      const showFiles = async ({item, value, target, ref, multiple, fileType}) => {
        // if(state.statusCode!==0){
        //   return
        // }
        Files.value.Data = Object.assign({}, {field: item, value: value})
        Files.value.dataTypeID = item.dataTypeID
        Files.value.todo()
        Files.value.multiple = multiple
        Files.value.fileType = fileType
        Files.value.title = fileType === 'images' ? '图片选择' : '附件选择'
        Files.value.status =state.statusCode
        Files.value.fileSize = item.fieldPrecision === 0 ? 8 : item.fieldPrecision
  
        state.selectFiels = {field: item, target: target, ref: ref}
      }
      const getSourceData = ({data, data2, C}) => {
        // data是选中的数组
        console.log("wwwwwww");
        const field = JSON.parse(state.selectDataGridTarget.field.componentFieldName)
        const target = state.selectDataGridTarget.target
        const keys = state.selectDataGridTarget.ref
       // console.log(field,target,keys);
        let isBT = true
        if (XEUtils.has(target, 'Seq')) {
          isBT = false
        }
        const tb = XEUtils.find(props.DT, item => item.tableName === keys)
        if (isBT) {
          XEUtils.objectEach(field, (item, key) => {
            target[key] = XEUtils.pluck(data, item.v).join(",")
            let extend = XEUtils.toStringJSON(target['Extend'])
            const F = state.Fields[keys].find(item => item.fieldName === key)
            if (F!==undefined && F['componentType'] === 3) {
              extend[key] = XEUtils.pluck(data, item.v).join(",")
            }
            target['Extend'] = XEUtils.toJSONString(extend)
          })
        } else {
          data.forEach(async (row, index) => {
  
            const newrow = await getDTdefault(keys,true)
            if (tb.layoutStyle.length > 0) {
              newrow[tb.layoutStyle[1]] = state.parentV
            }
            XEUtils.objectEach(field, (item, key) => {
              // 对象迭代器，只能用于遍历对象，性能高于 each
              if (row[item.v]) {
                newrow[key] = row[item.v]
              }
  
              let extend = XEUtils.toStringJSON(newrow['Extend'])
              const F = state.Fields[keys].find(item => item.fieldName === key)
              if (F!==undefined &&F['componentType'] === 3) {
                extend[key] = data[index][item.v]
              }
              newrow['Extend'] = XEUtils.toJSONString(extend)
            })
            
            XEUtils.objectEach(state.Fields[keys], (item, key) => {
              if (item.componentType === 9 && item.componentFieldName !== '') {
                newrow[item.fieldName] =  mathAlls(item, newrow)
              }
            })
            if (tb.layoutStyle.length>0&&newrow[tb.layoutStyle[0]] === newrow[tb.layoutStyle[1]]) {
              return false
            }
            if (index === 0) {
              XEUtils.objectEach(newrow, (item, key) => {
                if (item) {
                  target[key] = item
                }
              })
            } else {
              const $tb = state.itemRefs[keys]
              $tb.insertAt(newrow, -1)
  
            }
          })
        }
        ValueChange(target, state.Fields[keys], state.selectDataGridTarget.field.fieldName,keys)
      }
      const mathAlls=(item,data)=>{
          let gs=item.componentFieldName,d={}
          if(gs===''){return }
          if(gs[0]==='{'){
              d=XEUtils.toStringJSON(item.componentFieldName)
              gs=d['formula']
              if(d['one']===1 && !XEUtils.isEmpty(data[item.fieldName])){
                  return data[item.fieldName]
              }
          }
          let jgm=mathAll(gs, data)
  
         return   XEUtils.isNumber(jgm) ? XEUtils.toFixed(jgm, item.fieldPrecision) : jgm
        }
      // 移动端
      const addDataSou = (tableName) => {
        // console.log(tableName);
        state.selectTab = tableName
        const Max = XEUtils.max(state.DetailsData[state.selectTab], 'Seq')
        let seq = 0
        if (Max !== undefined) {
          seq = Max[['Seq']]
        }
        state.DetailsData[state.selectTab].push(getNewitem(state.selectTab, seq))
      }
      const getNewitem = (table, maxseq) => {
        const def = {}
        state.Fields[table].forEach(row => {
          def[row.fieldName] = null
        })
        def['Seq'] = maxseq + 1
        return def
      }
      const getFilesData = ({data, filesName, extdata}) => {
        state.selectFiels.target[state.selectFiels.field.fieldName] = data
        let extend = XEUtils.toStringJSON(state.selectFiels.target['Extend'])
        extend[state.selectFiels.field.fieldName] = filesName
        if (extdata.length > 0) {
          const field = JSON.parse(state.selectFiels.field.componentFieldName)
          for (let i = 0; i < extdata.length; i++) {
            if (i === 0) {
              XEUtils.objectEach(field, (item, key) => {
                state.selectFiels.target[key] = extdata[0][item]
              })
            } else {
              let rows = {}, ext = {}
              rows[state.selectFiels.field.fieldName] = data
              ext[state.selectFiels.field.fieldName] = filesName
              rows['Extend'] = XEUtils.toJSONString(ext)
              XEUtils.objectEach(field, (item, key) => {
                rows[key] = extdata[i][item]
              })
              // this.$refs[state.selectFiels.ref][0].insertAt(rows,-1)
            }
          }
        }
  
        state.selectFiels.target['Extend'] = XEUtils.toJSONString(extend)
      }
      const kk=(data)=>{
        console.log(data)
      }
      const Save = async () => {
  
        // if (state.formData.StatusCode !== 0) {
        //   ElMessage({
        //     message: '单据审核状态非初始状态.不能执行保存!',
        //     type: 'error',
        //   })
        //   return
        // }
        state.validateCheck = true
        const Data = {}
        Data['T'] = props.MT.templateID
        Data['D'] = await getDetailData()
        Data['M'] = await getMainData()
       // console.log(Data);
        if (!state.validateCheck) {
          return;
        }
        await editForm(route.params.templateCode, route.params.id, Data).then((response) => {
          let id=route.params.id
          if (response.code === 0) {
            ElMessage.success('单据操作成功')
            if (props.isNew) {
  
              proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
  
             id=response.data.id
              // proxy.mittBus.on('onTagsViewRefreshRouterView', url)
              // store.commit("sxclick", '/form/edit/:templateCode/:id-' + route.params.templateCode + "0")
              // router.push({params: {id: response.data.id}, replace: true})
            }
            const url = '/form/edit/' + route.params.templateCode + "/" + id
            router.push(url)
            //router.go(0);
            //reloadData(response.data.id)
  
          } else {
            ElMessage.error('单据操作出错')
          }
        })
  
      }
      const reloadData = (id) => {
        getForm(route.params.templateCode, id, {}).then(response => {
          state.AllData = response.data
          Load(2)
        })
      }
      const getDetailData = async () => {
        const Data = {}
        for (const tb of props.DT) {
          const indext = props.DT.indexOf(tb);
          let data = []
          Data[tb.tableName] = {DE: [], DD: [], DA: []}
          const errMap = await state.itemRefs[tb.tableName].validate()
          if (errMap) {
            state.validateCheck = false
            continue;
          }
          const olddata = state.OldDData[tb.tableName] || []
          // let maidseq = olddata.length > 0 ? XEUtils.max(olddata, item => item.Seq)['Seq'] : 0
          // console.log(props.isequipment);
          // if (props.isequipment) {
          const tabledata = state.itemRefs[tb.tableName].getRecordset()
          const deleteRecords = tabledata.removeRecords
          data = XEUtils.orderBy(tabledata.insertRecords.concat(tabledata.updateRecords), '_X_ROW_KEY')
  
          data = data.map((row, index) => {
            delete row['_X_ROW_KEY']
            delete row['_X_ROW_CHILD']
            delete row['children']
            return row
          })
          Data[tb.tableName].DD = deleteRecords
          // } else {
          //   data = state.DetailsData[tb.tableName].concat([])
          // }
          data.forEach(rowData => {
            let od = XEUtils.find(olddata, item => item.Seq === rowData.Seq)
            if (od === undefined) {
              Data[tb.tableName].DA.push(rowData)
            } else {
              const updateData = {}
              XEUtils.objectEach(od, (item, key) => {
                if (item !== rowData[key] && key !== 'Seq' && key !== 'RecordID') {
                  updateData[key] = rowData[key]
                }
              })
              if (!XEUtils.isEmpty(updateData)) {
                Data[tb.tableName].DE.push(XEUtils.assign(updateData, {
                  'RecordID': rowData['RecordID'],
                  'Seq': rowData['Seq']
                }))
              }
            }
          })
          // console.log(olddata);
          // olddata.forEach(row => {
          //   if (XEUtils.find(data, item => item.Seq === row.Seq) === undefined) {
          //     Data[tb.tableName].DD.push(row)
          //   }
          // })
  
        }
        return Data
      }
      const getMainData = async () => {
        const n = {}
        let data = {}
        const errMap = await refForm.value.validate()
        if (errMap) {
          state.validateCheck = false
          return
        }
        if (state.formData.RecordID === 0 || props.isNew) {
          data = state.formData
          data.RecordID = 0
          data.StatusCode = 0
        } else {
          XEUtils.objectEach(XEUtils.omit(state.formData, 'ChildTables'), (item, key) => {
            if ((key === 'Extend') || (state.OldMData[key] !== null && item !== state.OldMData[key]) || (state.OldMData[key] === null && item)) {
              data[key] = item
            }
          })
        }
        n[props.MT.tableName] = data
        const Data = XEUtils.clone(n, true)
        return Data
      }
      const sumNum = (list, field) => {
        let count = 0
  
        list.forEach(item => {
          count += Number(item[field])
        })
        return count
      }
      const showExpand = (table, row, lid) => {
        state.expandcfg = {id: lid, row: row}
        state.expandrow = row
        const $tb = state.itemRefs[table]
        $tb.toggleRowExpand(row)
      }
      const doExpand = (row, link,name) => {
        const TR= XEUtils.toStringJSON(link[0].torow)
        XEUtils.objectEach(TR,(fromfield ,tofield)=>{
          state.expandrow[tofield]=row[fromfield]
  
        })
        RunExpand({row: row, id: link[0].linkerID}).then(res => {
          if (res.code === 0) {
            ElMessage.success('操作成功')
          } else {
            ElMessage.error('操作出错' + res.msg)
          }
        })
  
      }
      const footerMethod = ({$table, columns, data}) => {
        const tableName = $table.props.id
        // state.itemRefs[tableName].clearTreeExpand()
        // data=state.itemRefs[tableName].getTableData().visibleData
  
        if (state.ShowFooter[tableName]) {
          return [
            columns.map((column, columnIndex) => {
              if (columnIndex === 0) {
                return '合计'
              }
              if (state.FooterFields[tableName].includes(column.property)) {
                return sumNum(data, column.property)
              }
              return null
            })
          ]
        }
  
      }
      const FLsubmitEvent= async ()=>{
          const errMap = await refForm.value.validate()
          if (errMap) {
              state.validateCheck = false
          }
          for (const tb of props.DT) {
              const errMap = await state.itemRefs[tb.tableName].validate()
              if (errMap) {
                  state.validateCheck = false
              }
          }
          if( state.validateCheck === false){
              return
          }
        const data=XEUtils.clone(state.fldata)
          data.opinion=XEUtils.trim(data.opinion)
          if(data.start){
              data.status=8
              data.opinion="重新提交"
          }
          if(data.status===7&&XEUtils.isEmpty(data.back)){
              ElMessage.error('请选择退回对象!')
              return
          }
          console.log(data)
            flowTodo(data).then(res=>{
                GetWF()
             // proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
        })
  
      }
      const addsign=(users)=>{
        if(users.length>0&&state.fldata.status===8){
            state.fldata['addsign']=users.map(user=>{
            return {id:user.id,name:user.userName}
          })
            FLsubmitEvent()
        }
  
      }
      const doedit=()=>{
        if (state.canEdit){
          if (!state.showedit){
            state.statusCode=99
            state.showedit=true
          }else{
            state.statusCode=0
            state.showedit=false
          }
        }else{
          state.statusCode=state.formData.StatusCode
          state.showedit=false
        }
        if(state.wkeditls){
          state.statusCode=0
          state.canEdit=true
          // state.wkedit=true
        }
      }
      const getShowFooter = (tableName) => {
        return state.ShowFooter[tableName]
      }
      const showFilesImage = (data) => {
        if (state.statusCode===99&&[5,6,10].includes(data.column.params.column.dataTypeID)){
          const column=data.column.params.column
          const row=data.row
          const TableName=data.$table.props.id
         showFiles({item:column ,value:row[column.fieldName],target:row,ref:TableName,multiple:[6].includes(data.column.params.column.dataTypeID),fileType:[6].includes(data.column.params.column.dataTypeID)?'files':'images'})
        }
      }
      const addTask = () => {
        if(state.formData.RecordID===0){
          ElMessage.error('请先保存后再提交')
          return
        }
        flowTodo( {TCode:route.params.templateCode,RID:route.params.id}).then(res=>{
          state.formData.StatusCode=1
          state.showedit=false
          GetWF()
        })
      }
        const handleCheck = (status) => {
  
            ElMessageBox.confirm(
                '是否确认' + (status > 0 ? "审核" : "反审") + "操作?",
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                formCheck({
                    template: route.name,
                    table: props.MT.tableName,
                    ids: state.formData.RecordID,
                    status: status
                }).then(res => {
                    ElMessage({
                        message: '操作成功',
                        grouping: true,
                        type: 'success',
                    })
                    proxy.mittBus.emit('onCurrentContextmenuClick', { contextMenuClickId: 0, ...route });
                })
            })
      }
      const parseCode=({event,field,data})=>{
        if(event.$event.keyCode===13){
          if(field.dataTypeID===8&& field.componentFieldName !== ''){
            const  codes=XEUtils.toStringJSON(field.componentFieldName)
            if(data[field.fieldName]&&data[field.fieldName].split(codes['separator']).length===codes['count']){
              data[field.fieldName]=data[field.fieldName].split(codes['separator'])[codes['size']]
            }
          }
        }
      }
      const approstatus = () => {
          setTimeout(()=>{
            state.fldata.opinion=state.opinion[state.fldata.status]+"  "
          },10)
      }
      const handlePrint  = async(item) => {
          state.validateCheck=true
          const errMap = await refForm.value.validate()
          if (errMap) {
              state.validateCheck = false
          }
          for (const tb of props.DT) {
              const errMap = await state.itemRefs[tb.tableName].validate()
              if (errMap) {
                  state.validateCheck = false
              }
          }
          if( state.validateCheck === false){
              return
          }
  
        let dm=state.formData
        dm['ChildTables']={}
        dm['ChildTables'][props.MT.tableName]=[state.formData]
         for (const tb of props.DT) {
             const tabledata = state.itemRefs[tb.tableName].getCheckboxRecords()
           if(tabledata.length>0){
             dm['ChildTables'][tb.tableName]=tabledata
           }else{
             dm['ChildTables'][tb.tableName]= state.itemRefs[tb.tableName].getData()
           }
         }
  
         const D= GetPrintFormat(item,props.Template,props.MT,props.DT, state.ApprovalData.tasks)
          const data={printData:D.item,rid:state.RecordID,DataSource:dm,Combo:props.Combo,maintable:props.MT,detailtable:props.DT}
         Print.value.Load(D.t,props.Template.templateCode,data)
      }
      const addproc = () => {
        Organization.value.showDialog()
      }
      const handlePrint2 = (type)=>{
        console.log();
        let value = null
        let formtable = {}
        for (const tb of props.DT) {
             const tabledata = state.itemRefs[tb.tableName].getCheckboxRecords()
           if(tabledata.length>0){
            formtable=tabledata
           }
         }
         if(route.path=='/Print/DY002'){
          value=formtable
         }else{
          value=state.formData
         }
        print3viewRef.value.itfo(props.alltable,JSON.parse(type.contento),value,state.DetailsData,type.id,route.path)
      }
      return {
        ...toRefs(state)
        , Load,
        getDefaults,handlePrint2,
        loadSelectRules,handlePrint,
        XEUtils,print3viewRef,
        DGE,rq,
        Files,
        Plus,Print,Organization,
        refForm,FLForm,
        insertTreeRow,addsign,ErrcellClassName,
        getextend,
        getShowFooter,
        showExpand,
        ValueChange,
        formatData,
        getMainData,
        getAutoCode,
        buttonsClick,
        showSource,
        showFiles,
        getSourceData,
        addDataSou,
        getNewitem,
        doExpand,
        runPostRule,
        runActRules,
        getFilesData,
        Save,mergeRowMethod,addTask,approstatus,parseCode,
        candelete,handleCheck,
        deleteTreeRow,
        GetSelectRules,
        getDetailData,
        footerMethod,
        extendTree, FLsubmitEvent,
        doedit,addproc,
        showFilesImage
      }
    }
  }
  </script>
  
  <style scoped>
  
  .plusA{ width: 35px;padding: 0px;font-size: 28px;color: #c9c9c9 !important;}
  
  
  </style>